/**
 * 导航工具函数
 * 提供防抖导航、安全导航等功能
 */
import { useRouter } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { globalAuth } from '@/composables/useAuth'
import { ElMessage } from 'element-plus'

// 导航状态管理
let isNavigating = false
let navigationTimer: NodeJS.Timeout | null = null
const navigationQueue = new Set<string>()

/**
 * 防抖导航函数
 * @param path 目标路径
 * @param delay 防抖延迟时间（毫秒）
 */
export function debouncedNavigate(path: string, delay: number = 300) {
  // 如果已经在导航队列中，忽略
  if (navigationQueue.has(path)) {
    return Promise.resolve()
  }

  navigationQueue.add(path)

  return new Promise<void>((resolve, reject) => {
    // 清除之前的定时器
    if (navigationTimer) {
      clearTimeout(navigationTimer)
    }

    navigationTimer = setTimeout(async () => {
      try {
        await safeNavigate(path)
        resolve()
      } catch (error) {
        reject(error)
      } finally {
        navigationQueue.delete(path)
      }
    }, delay)
  })
}

/**
 * 安全导航函数
 * @param path 目标路径
 */
export async function safeNavigate(path: string) {
  // 防止重复导航
  if (isNavigating) {
    console.warn('导航正在进行中，忽略重复请求')
    return
  }

  const router = useRouter()
  const userStore = useUserStore()

  isNavigating = true

  try {
    // 检查认证状态
    if (globalAuth.isInitializing.value) {
      ElMessage.info('正在验证身份，请稍候...')
      
      // 等待认证完成
      const maxWait = 5000
      const startTime = Date.now()
      
      while (globalAuth.isInitializing.value && (Date.now() - startTime) < maxWait) {
        await new Promise(resolve => setTimeout(resolve, 100))
      }
    }

    // 如果有认证错误，提示用户
    if (globalAuth.initializationError.value) {
      ElMessage.error('认证失败，请重新登录')
      await router.push('/login')
      return
    }

    // 执行导航
    await router.push(path)
  } catch (error: any) {
    console.error('导航失败:', error)
    
    // 处理不同类型的错误
    if (error.name === 'NavigationDuplicated') {
      // 重复导航，忽略
      return
    }
    
    if (error.response?.status === 401) {
      ElMessage.error('登录已过期，请重新登录')
      userStore.logout()
      await router.push('/login')
      return
    }
    
    ElMessage.error('页面跳转失败')
    throw error
  } finally {
    isNavigating = false
  }
}

/**
 * 检查路由权限
 * @param routeName 路由名称
 */
export function checkRoutePermission(routeName: string): boolean {
  const router = useRouter()
  const userStore = useUserStore()
  
  const route = router.getRoutes().find(r => r.name === routeName)
  if (!route) {
    return false
  }

  // 不需要认证的路由
  if (!route.meta?.requiresAuth) {
    return true
  }

  // 需要认证但未登录
  if (!userStore.isLoggedIn) {
    return false
  }

  // 检查角色权限
  if (route.meta?.roles && Array.isArray(route.meta.roles)) {
    const userRole = userStore.userInfo?.role
    if (!userRole || !route.meta.roles.includes(userRole)) {
      return false
    }
  }

  return true
}

/**
 * 获取用户可访问的菜单项
 */
export function getAccessibleMenus() {
  const router = useRouter()
  const userStore = useUserStore()
  
  return router.getRoutes().filter(route => {
    // 隐藏的菜单项
    if (route.meta?.hideInMenu) {
      return false
    }

    // 不需要认证的路由
    if (!route.meta?.requiresAuth) {
      return true
    }

    // 需要认证但未登录
    if (!userStore.isLoggedIn) {
      return false
    }

    // 检查角色权限
    if (route.meta?.roles && Array.isArray(route.meta.roles)) {
      const userRole = userStore.userInfo?.role
      if (!userRole || !route.meta.roles.includes(userRole)) {
        return false
      }
    }

    return true
  })
}

/**
 * 智能导航 - 根据用户角色导航到合适的页面
 */
export async function smartNavigate() {
  const userStore = useUserStore()
  
  if (!userStore.isLoggedIn) {
    await safeNavigate('/login')
    return
  }

  const userRole = userStore.userInfo?.role
  
  // 根据角色导航到默认页面
  switch (userRole) {
    case 'admin':
      await safeNavigate('/dashboard')
      break
    case 'teacher':
      await safeNavigate('/dashboard')
      break
    case 'student':
      await safeNavigate('/dashboard')
      break
    default:
      await safeNavigate('/dashboard')
  }
}

/**
 * 清理导航状态
 */
export function clearNavigationState() {
  isNavigating = false
  navigationQueue.clear()
  
  if (navigationTimer) {
    clearTimeout(navigationTimer)
    navigationTimer = null
  }
}

/**
 * 获取导航状态
 */
export function getNavigationState() {
  return {
    isNavigating,
    queueSize: navigationQueue.size,
    isInitializing: globalAuth.isInitializing.value,
    hasError: !!globalAuth.initializationError.value
  }
}
